package com.zl.learning.json.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class GsonTest7 {
    private Gson gson = new Gson();

    @Test
    public void test1() {
        User u = new User();
        u.setId(1);
        u.setName("zhansan");
        String val = gson.toJson(u);
        System.out.println(val);
        Gson g2 = new GsonBuilder().serializeNulls().create();
        System.out.println(g2.toJson(u));
    }

    @Test
    public void test2() {
        String val = "{\"id\":1,\"name\":\"zhansan\"}";
        User u = gson.fromJson(val, User.class);
        System.out.println(gson.toJson(u));
    }

    @Test
    public void test3() {
        Random random = new Random();
        System.out.println(random.nextInt(2));
        System.out.println(random.nextInt(2));
        System.out.println(random.nextInt(2));
        System.out.println(random.nextInt(2));
        System.out.println(random.nextInt(2));
        System.out.println(random.nextInt(2));
    }

    @Test
    public void test4() {
        long t = System.currentTimeMillis();
        System.out.println(String.valueOf(t).substring(5).length());
    }

    @Test
    public void test5() {
        List<User> users = Arrays.asList(new User(),new User());
        users = users.stream().map(r->r.setNickName("zzz")).collect(Collectors.toList());
        String usersStr = gson.toJson(users);
        System.out.println(usersStr);
        users = gson.fromJson(usersStr,new TypeToken<List<User>>(){}.getType());
        System.out.println(gson.toJson(users));
    }

    @Test
    public void test6(){
        User u = new User();
        u.setId(1);
        u.setName("aaa");
        u.setNickName("");
//        Gson g = new GsonBuilder().serializeNulls().create();
        Gson g = new Gson();
        System.out.println(g.toJson(u));
    }

    public static class User {

        private int id;
        private String name;
        private String nickName;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public User setName(String name) {
            this.name = name;
            return this;
        }

        public String getNickName() {
            return nickName;
        }

        public User setNickName(String nickName) {
            this.nickName = nickName;
            return this;
        }
    }
}
